package com.nbsaas.boot.lock.impl;

import com.nbsaas.boot.lock.api.CountingLockService;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.LongAdder;

public class ReentrantLockCountingService extends ReentrantLockService implements CountingLockService {

    private final ConcurrentMap<String, LongAdder> lockCountMap = new ConcurrentHashMap<>();
    private final LongAdder totalLockCount = new LongAdder();

    @Override
    public boolean lock(String key) {
        if (super.lock(key)) {
            lockCountMap.computeIfAbsent(key, k -> new LongAdder()).increment();
            totalLockCount.increment();
            return true;
        }
        return false;
    }

    @Override
    public boolean unlock(String key) {
        if (super.unlock(key)) {
            LongAdder count = lockCountMap.get(key);
            if (count != null) {
                count.decrement();
                if (count.intValue() == 0) {
                    lockCountMap.remove(key);
                    lockMap.remove(key); // 从父类的 lockMap 中移除锁
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public int getLockCount(String key) {
        LongAdder count = lockCountMap.get(key);
        return count == null ? 0 : count.intValue();
    }

    @Override
    public int getTotalLockCount() {
        return totalLockCount.intValue();
    }

    @Override
    public int getCurrentLockCount() {
        return lockMap.size();
    }
}
